import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProDescriptions, ProFormCheckbox,
    ProFormText,
    ProTable,
    ProFormDateRangePicker, ProFormDigit, ProFormUploadButton, ProFormSelect, ProFormRadio, ProFormDateTimePicker,
} from '@ant-design/pro-components';
import {Button, Drawer, Input, message, Modal, Tag, Badge, Space, Statistic, Select, Radio, Flex, Progress} from 'antd';
import React, {useRef, useState} from 'react';
import type {OrganizationInfo, StorageListItem} from './data';
import {storageList, storageAdd, storageEdit, storageSelectList, storageDelete} from './service';
import {dataCenterSelectList} from "@/pages/power/data-center-list/service";
import {organizationSelectList} from "@/pages/organization/org-list/service";
import {organizationOrderAdd} from "@/pages/power/resource-activate/service";
import {useAccess, Access} from 'umi';
import {NetworkHostComputerListItem, NetworkListItem} from "@/pages/power/network/data";

const {confirm} = Modal;

const handleAdd = async (fields: StorageListItem) => {
    const hide = message.loading('正在添加');

    try {
        await storageAdd({...fields});
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};
/**
 * 更新节点
 *
 * @param fields
 */

export type FormValueType = {
    target?: string;
    template?: string;
    type?: string;
    time?: string;
    frequency?: string;
} & Partial<StorageListItem>;


const handleUpdate = async (fields: FormValueType, currentRow?: StorageListItem) => {
    const hide = message.loading('正在配置');

    try {
        await storageEdit({
            ...currentRow,
            ...fields,
        });
        hide();
        message.success('配置成功');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};


const handleFenpei = async (fields: FormValueType, currentRow?: StorageListItem) => {
    const hide = message.loading('正在配置');

    try {
        await organizationOrderAdd({
            ...currentRow,
            ...fields,
        });
        hide();
        message.success('配置成功');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};


/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: StorageListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
        await storageDelete({
            storageIds: selectedRows.map((row) => row.storageId),
        });
        hide();
        message.success('删除成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

const StorageList: React.FC = () => {
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    /** 分布更新窗口的弹窗 */
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [fenpeiModalVisible, handleFenpeiModalVisible] = useState<boolean>(false);
    const [addContractModalVisible, handleAddContractVisible] = useState<boolean>(false);
    const [showDetail, setShowDetail] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<StorageListItem>();
    const [selectedRowsState, setSelectedRows] = useState<StorageListItem[]>([]);
    const access = useAccess();
    const [storageOrganizationModalVisible, handleStorageOrganizationModalVisible] = useState<boolean>(false);
    const rowSelection = access.isSystem
        ? {
            onChange: (_: any, selectedRows: React.SetStateAction<StorageListItem[]>) => {
                setSelectedRows(selectedRows);
            },
        }
        : false;


    const storageOrganizationColumns: ProColumns<OrganizationInfo>[] = [
        {
            title: '租户名称',
            dataIndex: "organizationName",
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '分配容量',
            dataIndex: 'resourceDesc',
            search: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '分配时间',
            dataIndex: "createdAt",
            search: false,
            valueType: 'text',
            ellipsis: true, // 关闭自动换行
        },
    ];
    /** 国际化配置 */
    const columns: ProColumns<StorageListItem>[] = [
        {
            title: '所属资源池',
            dataIndex: "dataCenterId",
            valueType: 'select',
            search: true,
            hidden: true,
            request: async () => {
                const result = await dataCenterSelectList({});
                return (
                    result.data?.map((item) => ({
                        label: item.name,
                        value: item.dataCenterId,
                    })) || []
                );
            },
        },
        {
            title: '所属资源池',
            dataIndex: "dataCenterName",
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '存储ID',
            dataIndex: 'storageId',
            search: false,
            hidden: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '存储名称',
            dataIndex: 'storageName',
            search: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '文件系统类型',
            dataIndex: 'storageType',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '容量',
            dataIndex: 'storageSizeDesc',
            search: false,
            render: (value, record, index) => {
                return `${record.storageSize}${record.storageUnit}`
            },
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '售卖容量',
            dataIndex: 'sellCapacity',
            search: false,
            ellipsis: true, // 关闭自动换行
            hidden: true,
        },
        {
            title: '售卖容量',
            dataIndex: 'sellCapacityPercent',
            search: false,
            render: (value, record, index) => {
                return <Flex vertical gap="small" style={{width: 90}}>
                    <Progress percent={record.sellCapacityPercent} size="small"/>
                </Flex>
            },
        },
        {
            title: '售卖详情',
            dataIndex: 'organizationList',
            search: false,
            ellipsis: true, // 关闭自动换行
            hidden: false,
            render: (value, record, index) => {
                if (record.organizationList?.length > 0) {
                    return <a
                        key="organizationList"
                        onClick={() => {
                            setCurrentRow(record);
                            handleStorageOrganizationModalVisible(true);
                        }}
                    >
                        查看
                    </a>
                } else {
                    return ''
                }
            }
        },
        {
            title: '连接信息',
            // dataIndex: 'admin',
            dataIndex: 'connInfo',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '设备类型',
            dataIndex: 'deviceType',
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '硬盘类型',
            dataIndex: 'hardDiskType',
            valueType: 'text',
            search: false,
            hidden: true,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            hidden: access.isCustom,
            render: (_, record) => {
                return [
                    <a
                        key="config"
                        onClick={() => {
                            handleUpdateModalVisible(true);
                            setCurrentRow(record);
                        }}
                    >
                        编辑
                    </a>,
                    <a
                        key="fenpei"
                        onClick={() => {
                            handleFenpeiModalVisible(true);
                            setCurrentRow(record);
                        }}
                    >
                        分配
                    </a>,
                ]
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<StorageListItem, API.ListPagination>
                headerTitle="存储列表"
                actionRef={actionRef}
                rowKey="storageId"
                search={{
                    labelWidth: 90,
                }}
                scroll={{x: true}}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined/> 新建
                    </Button>,
                ]}
                request={storageList}
                columns={columns}
                rowSelection={rowSelection}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '删除存储',
                                // icon: <ExclamationCircleFilled />,
                                content: '删除存储前，请确认存储关联的订单资源已清除，是否现在删除?',
                                onOk() {
                                    handleRemove(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量删除
                    </Button>
                </FooterToolbar>
            )}

            <ModalForm
                title="添加存储"
                width="550px"
                open={createModalVisible}
                onVisibleChange={handleModalVisible}
                onFinish={async (value) => {
                    const success = await handleAdd(value as StorageListItem);
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}
            >
                <ProFormSelect
                    label="所属资源池"
                    name="dataCenterId"
                    rules={[
                        {
                            required: true,
                            message: '请选择资源池',
                        },
                    ]}
                    placeholder="请选择资源池"
                    request={async () => {
                        const res = await dataCenterSelectList({});
                        return res.data.map((item) => ({
                            label: item.name,
                            value: item.dataCenterId,
                        }));
                    }}
                />
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '存储名称为必填项',
                        },
                    ]}
                    // width="md"
                    name="storageName"
                    label="存储名称"
                />
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '文件系统类型为必填项',
                        },
                    ]}
                    // width="md"
                    name="storageType"
                    label="文件系统类型"
                />
                <ProFormDigit
                    label="存储存量"
                    name="storageSize"
                    rules={[
                        {
                            required: true,
                            message: '请输入存储存量',
                        },
                    ]}
                    width={200}
                    placeholder="请输入存储大小"
                />
                <ProFormRadio.Group
                    name="storageUnit"
                    label="存储单位"
                    radioType="button"
                    rules={[
                        {
                            required: true,
                            message: '请选择存储单位',
                        },
                    ]}
                    options={[
                        {
                            label: 'GB',
                            value: 'GB',
                        },
                        {
                            label: 'TB',
                            value: 'TB',
                        },
                        {
                            label: 'PB',
                            value: 'PB',
                        },
                    ]}
                />
                <ProFormText
                    // width="md"
                    name="connInfo"
                    label="连接信息"
                />

                <ProFormText
                    // width="md"
                    name="deviceType"
                    label="设备类型"
                />

                <ProFormText
                    // width="md"
                    name="hardDiskType"
                    label="硬盘类型"
                />
            </ModalForm>
            <ModalForm
                title="编辑存储信息"
                width="550px"
                open={updateModalVisible}
                onVisibleChange={handleUpdateModalVisible}
                onFinish={async (value) => {
                    const success = await handleUpdate(value, currentRow);
                    if (success) {
                        handleUpdateModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}
                initialValues={{
                    storageId: currentRow?.storageId,
                    storageName: currentRow?.storageName,
                    connInfo: currentRow?.connInfo,
                    deviceType: currentRow?.deviceType,
                    storageType: currentRow?.storageType,
                    storageSize: currentRow?.storageSize,
                    storageUnit: currentRow?.storageUnit,
                    hardDiskType: currentRow?.hardDiskType,
                }}
            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '存储名称为必填项',
                        },
                    ]}
                    // width="md"
                    name="storageName"
                    label="存储名称"
                />
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '文件系统类型为必填项',
                        },
                    ]}
                    // width="md"
                    name="storageType"
                    label="文件系统类型"
                />
                <ProFormDigit
                    width="md"
                    name="storageSize"
                    label="存储容量"
                    fieldProps={
                        {
                            addonAfter: currentRow?.storageUnit,
                        }
                    }
                />
                <ProFormText
                    // width="md"
                    name="connInfo"
                    label="连接信息"
                />

                <ProFormText
                    // width="md"
                    name="deviceType"
                    label="设备类型"
                />

                <ProFormText
                    // width="md"
                    name="hardDiskType"
                    label="硬盘类型"
                />
            </ModalForm>

            <ModalForm
                title="分配存储"
                width="650px"
                open={fenpeiModalVisible}
                onVisibleChange={handleFenpeiModalVisible}
                onFinish={async (value) => {
                    const success = await handleFenpei(value as StorageListItem);
                    if (success) {
                        handleFenpeiModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}
                initialValues={{
                    storageId: currentRow?.storageId,
                    storageName: currentRow?.storageName,
                    connInfo: currentRow?.connInfo,
                    deviceType: currentRow?.deviceType,
                    storageType: currentRow?.storageType,
                    storageSize: currentRow?.storageSize,
                    storageUnit: currentRow?.storageUnit,
                    hardDiskType: currentRow?.hardDiskType,
                    resourceType: 'storage',
                    resourceId: currentRow?.storageId,
                }}
            >
                <ProFormText
                    name="resourceType"
                    label="资源类型"
                    disabled={true}
                    hidden={true}
                />
                <ProFormText
                    name="resourceId"
                    label="资源ID"
                    disabled={true}
                    hidden={true}
                />
                <ProFormSelect
                    label="租户"
                    name="organizationId"
                    style={{width: 200}}
                    request={async () => {
                        const res = await organizationSelectList({});
                        return res.data.map((item) => ({
                            label: item.name,
                            value: item.organizationId,
                        }));
                    }}
                    placeholder="请选择租户信息"
                    rules={[{required: true, message: '请选择租户信息'}]}
                />
                <ProFormDigit
                    label="分配容量"
                    name="storageSize"
                    rules={[
                        {
                            required: true,
                            message: '请输入分配存储容量',
                        },
                    ]}
                    width={200}
                    placeholder="请输入分配存储容量"
                />
                <ProFormRadio.Group
                    name="storageUnit"
                    label="单位"
                    radioType="button"
                    rules={[
                        {
                            required: true,
                            message: '请选择存储单位',
                        },
                    ]}
                    options={[
                        {
                            label: 'GB',
                            value: 'GB',
                        },
                        {
                            label: 'TB',
                            value: 'TB',
                        },
                        {
                            label: 'PB',
                            value: 'PB',
                        },
                    ]}
                />
                {/*<ProFormRadio.Group*/}
                {/*    name="billingCycle"*/}
                {/*    label="计费周期"*/}
                {/*    rules={[*/}
                {/*        {*/}
                {/*            required: true,*/}
                {/*            message: '请选择计费周期',*/}
                {/*        },*/}
                {/*    ]}*/}
                {/*    options={[*/}
                {/*        {*/}
                {/*            label: '每小时',*/}
                {/*            value: 'hour',*/}
                {/*        },*/}
                {/*        {*/}
                {/*            label: '每天',*/}
                {/*            value: 'day',*/}
                {/*        },*/}
                {/*        {*/}
                {/*            label: '每月',*/}
                {/*            value: 'month',*/}
                {/*        },*/}
                {/*    ]}*/}
                {/*/>*/}
                {/*<ProFormDigit*/}
                {/*    label="单价"*/}
                {/*    name="unitPriceNumber"*/}
                {/*    rules={[*/}
                {/*        {*/}
                {/*            required: true,*/}
                {/*            message: '请输入单价',*/}
                {/*        },*/}
                {/*    ]}*/}
                {/*    width={200}*/}
                {/*    fieldProps={{addonAfter: "元"}}*/}
                {/*    placeholder="请输入单价"*/}
                {/*/>*/}
                {/*<ProFormDateTimePicker*/}
                {/*    label="开始计费时间（可选）"*/}
                {/*    width="md"*/}
                {/*    name="start"*/}
                {/*    placeholder={'开始日期'}*/}
                {/*    // disabled={true}*/}
                {/*/>*/}
            </ModalForm>

            <Modal
                title="租户分配信息"
                width="650px"
                open={storageOrganizationModalVisible}
                // onVisibleChange={handleNetworkHostComputerModalVisible}
                onOk={() => handleStorageOrganizationModalVisible(false)}
                onCancel={() => handleStorageOrganizationModalVisible(false)}
                // okText="确认"
                // cancelText="取消"
            >
                <ProTable<NetworkListItem, API.ListPagination>
                    rowKey="orderId"
                    search={false}
                    toolBarRender={() => []}
                    scroll={{x: true}}
                    columns={storageOrganizationColumns}
                    rowSelection={false}
                    options={false}
                    dataSource={currentRow?.organizationList}
                />
            </Modal>

            <Drawer
                width={600}
                open={showDetail}
                onClose={() => {
                    setCurrentRow(undefined);
                    setShowDetail(false);
                }}
                closable={false}
            >
                {currentRow?.storageName && (
                    <ProDescriptions<StorageListItem>
                        column={2}
                        title={currentRow?.storageName}
                        request={async () => ({
                            data: currentRow || {},
                        })}
                        params={{
                            id: currentRow?.storageName,
                        }}
                        columns={columns as ProDescriptionsItemProps<StorageListItem>[]}
                    />
                )}
            </Drawer>
        </PageContainer>
    );
};

export default StorageList;
